﻿using System;
using System.ServiceModel.Web;

namespace SimpleServiceBus.EndpointManagement.Server.Wcf
{
    public class WebOperationContextQueryStringProvider : IQueryStringProvider
    {
        public T GetQueryStringParameter<T>(string queryStringKey)
        {
            return GetQueryStringParameter<T>(queryStringKey, default(T));
        }

        public T GetQueryStringParameter<T>(string queryStringKey, T defaultValue)
        {
            if (WebOperationContext.Current != null)
            {
                object val =
                    WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters[queryStringKey];
                if (val == null)
                    return defaultValue;
                if (typeof(T).IsAssignableFrom(val.GetType()))
                    return (T) val;
                try
                {
                    return (T)Convert.ChangeType(val, typeof (T));
                }
                catch (Exception)
                {
                    return defaultValue;
                }
            }
            throw new InvalidOperationException("No WebOperationContext exists to supply QueryString parameters");
        }
    }
}
